package com.banciyuan.bcywebview.biz.main.mainpage;

import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.main.MainActivity;
import com.banciyuan.bcywebview.biz.main.mainpage.maincircle.MainCircleFragment;
import com.banciyuan.bcywebview.biz.main.mainpage.timeline.TimelineFragment;
import com.banciyuan.bcywebview.biz.post.ScreenShots;
import com.banciyuan.bcywebview.biz.post.StartPostActivity;
import com.banciyuan.bcywebview.biz.setting.MainSettingHelper;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import java.util.LinkedList;
import java.util.List;

import de.greenrobot.daoexample.model.AppSetting;

public class MainPageFragment extends BaseContainerFragment implements View.OnClickListener, BaseWatcher {

    private List<Fragment> mList = new LinkedList<>();
    public static final int TAG = 0;
    private ViewPager mPager;
    private MyAdapter mAdapter;
    private MainCircleFragment mainCircleFragment;
    private TimelineFragment timelineFragment;
    private FragmentManager fm;
    private View rootView;
    private View viewTimelineNotice;
    private AppSetting appSetting;
    private PopupWindow filterPop;
    private TextView mTitle;
    private ImageView mPullDown;

    private TabLayout mTabLayout;

    private View publish;
    private View login;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.mainpage_layout, container, false);
        fm = getChildFragmentManager();
        getFragment();
        initArgs();
        initUi(rootView);
        initData();
        initAction();
        return rootView;
    }

    private View getTabCustomView() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View rootView = inflater.inflate(R.layout.main_page_item_one, null);
        mPullDown = (ImageView) rootView.findViewById(R.id.pull_pink);
        mTitle = (TextView) rootView.findViewById(R.id.tab_item);
        viewTimelineNotice = rootView.findViewById(R.id.red_dot);
        return rootView;
    }

    @Override
    protected void initArgs() {
        BaseObserver.getInstance().addWatcher(MainPageFragment.class, this);
    }

    @Override
    protected void initUi(View rootview) {
        mTabLayout = (TabLayout) rootview.findViewById(R.id.tablayout);
        publish = rootview.findViewById(R.id.view_publish);
        login = rootview.findViewById(R.id.view_login);
        mPager = (ViewPager) rootview.findViewById(R.id.pager);
        mPager.setOffscreenPageLimit(2);
        mList.add(timelineFragment);
        mList.add(mainCircleFragment);
        mAdapter = new MyAdapter(getChildFragmentManager());
        mPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mPager);
        TabLayout.Tab tab = mTabLayout.getTabAt(0);
        if (tab != null) {
            tab.setCustomView(getTabCustomView());
            if (tab.getCustomView() != null) {
                ((View) (tab.getCustomView().getParent())).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mTabLayout.getSelectedTabPosition() == 0) {
                            showTimelineSelectorPop();
                        } else {
                            mPager.setCurrentItem(0);
                        }
                    }
                });
            }
        }
        mTitle.setTextColor(getResources().getColor(R.color.pink));
        publish.setOnClickListener(this);
        login.setOnClickListener(this);

        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            publish.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
        } else {
            publish.setVisibility(View.GONE);
            login.setVisibility(View.VISIBLE);
        }
    }

    private class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0) {
                return getString(R.string.timeline_multi);
            } else {
                return getString(R.string.mine_circle_with_space);
            }
        }
    }

    @Override
    protected void initAction() {
        mTabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                switch (tab.getPosition()) {
                    case 1:
                        mTitle.setTextColor(getResources().getColor(R.color.mine_textcolor));
                        if (viewTimelineNotice.getVisibility() == View.GONE) {
                            mPullDown.setVisibility(View.INVISIBLE);
                        } else {
                            mPullDown.setVisibility(View.GONE);
                        }
                        mPullDown.setImageResource(R.drawable.arrow_down_pink);
                        StatService.onEvent(getActivity(), EventConstants.CIRCLE_ID, EventConstants.CIRCLE_EVENT);
                        break;
                    case 0:
                        mTitle.setTextColor(getResources().getColor(R.color.pink));
                        if (viewTimelineNotice.getVisibility() == View.GONE) {
                            mPullDown.setVisibility(View.VISIBLE);
                        }
                        break;
                }
            }
        });
    }

    private void getFragment() {
        timelineFragment = new TimelineFragment();
        mainCircleFragment = new MainCircleFragment();
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.MAINSETTING_EVENT:
                appSetting = (AppSetting) object;
                if (null == appSetting || null == appSetting.getTimeline()) {
                    break;
                }
                setTraitorIcon();
                if (Boolean.valueOf(message) && mTabLayout != null) {
                    mTabLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            reSetTimelineData();
                        }
                    }, getActivity().getResources().getInteger(R.integer.slide_animation_duration));
                }
                break;
            case BaseObserver.MAINSETTING_NOTICE_EVENT:
                viewTimelineNotice.setVisibility(View.VISIBLE);
                mPullDown.setVisibility(View.GONE);
                break;
            case BaseObserver.MAINSETTING_UNNOTICE_EVENT:
                viewTimelineNotice.setVisibility(View.GONE);
                mPullDown.setVisibility(View.VISIBLE);
                break;
            case BaseObserver.FOCUS_USER_HAS_POST:
                if (checkOver24() && StringUtil.notNullEqual(mTitle.getText().toString(), getString(R.string.timeline_multi))) {
                    viewTimelineNotice.setVisibility(View.VISIBLE);
                    mPullDown.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void setTraitorIcon() {
        if (mTabLayout.getTabCount() > 0) {
            if (appSetting.getTimeline().getTraitor() == 0) {
                if (mTitle != null) {
                    mTitle.setText(getString(R.string.timeline_multi));
                }
            } else {
                if (mTitle != null) {
                    mTitle.setText(getString(R.string.timeline_focused_only));
                }
            }
        }
    }


    @Override
    public void selfUpdateData() {
        try {
            Fragment currentFragment = mAdapter.getItem(mPager.getCurrentItem());
            ((BaseContainerFragment) currentFragment).selfUpdateData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_publish:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ScreenShots screenShots = new ScreenShots(getActivity());
                        screenShots.takeShot();
                    }
                });
                gotoUtil.gotoAct(getActivity(), StartPostActivity.class, "main");
                getActivity().overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.view_login:
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                break;
        }
    }

    private void showTimelineSelectorPop() {
        final View contentView = View.inflate(getActivity(), R.layout.pop_selector_timeline_type, null);
        filterPop = new PopupWindow(contentView, -1, -1, true);
        filterPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        filterPop.setOutsideTouchable(true);
        final View viewMultiTimeline = contentView.findViewById(R.id.view_multi_timeline);
        final View viewFocusedOnly = contentView.findViewById(R.id.view_focused_only);
        final View multiSelected = contentView.findViewById(R.id.multi_selected);
        final View focusSelected = contentView.findViewById(R.id.focus_selected);
        final View split = contentView.findViewById(R.id.split);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            split.setVisibility(View.GONE);
        } else {
            split.setVisibility(View.VISIBLE);
        }
        final TextView multiText = (TextView) contentView.findViewById(R.id.multi_title);
        final TextView focusText = (TextView) contentView.findViewById(R.id.focus_title);
        final View focusNotice = contentView.findViewById(R.id.view_focus_timeline_notice);
        final View multiNotice = contentView.findViewById(R.id.view_mulit_timeline_notice);
        if (null != appSetting && null != appSetting.getTimeline()) {
            if (appSetting.getTimeline().getTraitor() == 1) {
                focusSelected.setVisibility(View.VISIBLE);
                multiSelected.setVisibility(View.GONE);
                focusText.setTextColor(getResources().getColor(R.color.pink));
                multiText.setTextColor(getResources().getColor(R.color.mine_textcolor));

                focusText.setTypeface(Typeface.DEFAULT_BOLD);
                multiText.setTypeface(Typeface.DEFAULT);

            } else {
                focusSelected.setVisibility(View.GONE);
                multiSelected.setVisibility(View.VISIBLE);
                focusText.setTextColor(getResources().getColor(R.color.mine_textcolor));
                multiText.setTextColor(getResources().getColor(R.color.pink));

                focusText.setTypeface(Typeface.DEFAULT);
                multiText.setTypeface(Typeface.DEFAULT_BOLD);
            }
            viewMultiTimeline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appSetting.getTimeline().getTraitor() == 1) {
                        setMainSetting(0);
                        focusSelected.setVisibility(View.GONE);
                        multiNotice.setVisibility(View.GONE);
                        multiSelected.setVisibility(View.VISIBLE);

                        focusText.setTextColor(getResources().getColor(R.color.mine_textcolor));
                        multiText.setTextColor(getResources().getColor(R.color.pink));

                        focusText.setTypeface(Typeface.DEFAULT);
                        multiText.setTypeface(Typeface.DEFAULT_BOLD);

                        viewTimelineNotice.setVisibility(View.GONE);
                        mPullDown.setVisibility(View.VISIBLE);
                    }
                }
            });
            viewFocusedOnly.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appSetting.getTimeline().getTraitor() == 0) {
                        setMainSetting(1);
                        focusSelected.setVisibility(View.VISIBLE);
                        multiSelected.setVisibility(View.GONE);
                        focusNotice.setVisibility(View.GONE);

                        focusText.setTextColor(getResources().getColor(R.color.pink));
                        multiText.setTextColor(getResources().getColor(R.color.mine_textcolor));
                        focusText.setTypeface(Typeface.DEFAULT_BOLD);
                        multiText.setTypeface(Typeface.DEFAULT);

                        viewTimelineNotice.setVisibility(View.GONE);
                        mPullDown.setVisibility(View.VISIBLE);
                    }
                }
            });
            if (multiSelected.getVisibility() == View.GONE) {
                multiNotice.setVisibility(viewTimelineNotice.getVisibility());
            }
            if (focusNotice.getVisibility() == View.GONE) {
                focusNotice.setVisibility(viewTimelineNotice.getVisibility());
            }
            contentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    filterPop.dismiss();
                }
            });
            filterPop.setAnimationStyle(R.style.popwin_anim_style_fast);
            filterPop.showAtLocation(rootView, Gravity.CENTER_HORIZONTAL, 0, 0);
        }
    }

    private void setMainSetting(final int is_open) {
        MainSettingHelper.setMainSetting(getActivity(), MainSettingHelper.TYPE_TRAITOR, is_open, new MainSettingHelper.MainSettingListener() {
            @Override
            public void getMainSettingSuccess(AppSetting appSetting) {
            }

            @Override
            public void setMainSettingSuccess(String response) {
                MainPageFragment.this.appSetting.getTimeline().setTraitor(is_open);
                setTraitorIcon();
                if (null != filterPop)
                    filterPop.dismiss();
                reSetTimelineData();
            }

            @Override
            public void onFail() {
            }
        });
    }

    private void reSetTimelineData() {
        if (null != timelineFragment)
            timelineFragment.resetTimeline();
    }

    private boolean checkOver24() {
        long time = SPHelper.getLong(getActivity(), SPConstant.FOCUS_USER_HAS_POST, 0);
        long now = System.currentTimeMillis();
        if ((now - time) / 1000 > 24 * 3600) {
            SPHelper.putLong(getActivity(), SPConstant.FOCUS_USER_HAS_POST, now);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        for (Fragment f : mList) {
            f.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onDestroy() {
        BaseObserver.getInstance().removeWatcher(MainActivity.class);
        super.onDestroy();
    }
}
